/**
 * @Description: 公众号微信授权登录
 * @Author: wrysunny
 * @Date: 2024-11-18 16:49:57
 * @LastEditor: wrysunny
 * @LastEditTime: 2024-12-12 10:15:31
 */
import {
	ref
} from "vue";
import {
	getTokenByH5
} from "@/config/api/user";
import {
	onLoad
} from '@dcloudio/uni-app';
import {
	useLoginStore
} from '@/store/login';
import config from "@/config/common";
import useUserInfo from "./useUserInfo";
import useMember from "./useMember";
import common from "@/config/common";
/**
 * @description: H5微信登录
 * @return {Object}
 */
const useH5WxLogin = () => {
	const code = ref('')
	const store = useLoginStore();
	/**
	 * @description: 获取微信code
	 * @return
	 */
	const getWxCodeByH5 = () => {
		const appid = config.appid;
		const redirect_uri = encodeURIComponent(common.redirect_uri);
		const url =
			`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
		window.location.href = url;
	}

	/**
	 * @description: 获取url中的参数
	 * @return {Object} 参数对象
	 */
	const getQuery = () => {
		// 获取当前url
		let url = window.location.search;
		// 创建theRequest对象
		let theRequest = new Object();
		// 如果当前url中包含‘?’
		if (url.indexOf("?") != -1) {
			// 获取url中‘?’之后的字符串
			let str = url.substr(1);
			// 将字符串按照‘&’分割
			let strs = str.split("&");
			// 遍历分割后的字符串数组
			for (let i = 0; i < strs.length; i++) {
				// 将每个字符串按照‘=’分割，以此获取参数名和参数值
				theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
			}
		}
		// 返回theRequest对象
		return theRequest;
	}
	const {
		getUserInfoFn
	} = useUserInfo();
	const {
		getUserMemberInfo
	} = useMember();
	const wxLoginByH5 = async () => {
		try {
			const res = await getTokenByH5({
				code: code.value,
				inviteUserId: uni.getStorageSync('pid') || null
			});
			if (res.code == 200) {
				store.userInfo = res.data;
				uni.setStorageSync('token', res.data.token);
				uni.removeStorageSync('pid')
				store.loginState = false;
				await getUserInfoFn()
				await getUserMemberInfo();
			}
		} catch (e) {
			//TODO handle the exception
		}
	}

	onLoad(() => {
		// #ifdef H5
		code.value = getQuery().code;
		if (code.value && !uni.getStorageSync('token')) {
			wxLoginByH5();
		}
		// #endif
	})
	return {
		wxLoginByH5,
		getWxCodeByH5
	}
};

export default useH5WxLogin;